using System;
using System.Diagnostics;
using System.Globalization;
using WPFTemplateLib.WpfConverters.Core;
/*
* 源码已托管：https://gitee.com/dlgcy/WPFTemplateLib
*/
namespace WPFTemplateLib.WpfConverters
{
	/// <summary>
	/// [转换器] 参考值转实际值
	/// <example>
	///	<code>
	///	Canvas.Top="{Binding Position, 
	///	Converter={converters:ReferenceValueToRealValueConverter IsReversed=True, RealValueMin=430, RealValueMax=460, RefValueMin=0, RefValueMax=100}}"
	/// </code>
	/// </example>
	/// </summary>
	public class ReferenceValueToRealValueConverter : ValueConverterBase
	{
		/// <summary>
		/// 参考值（数据）最小值
		/// </summary>
		public double RefValueMin { get; set; }

		/// <summary>
		/// 参考值（数据）最大值
		/// </summary>
		public double RefValueMax { get; set; }

		/// <summary>
		/// 实际值（UI）最小值
		/// </summary>
		public double RealValueMin { get; set; }

		/// <summary>
		/// 实际值（UI）最大值
		/// </summary>
		public double RealValueMax { get; set; }

		/// <summary>
		/// 是否调转方向
		/// </summary>
		public bool IsReversed { get; set; }

		/// <summary>
		/// 参考值大于最大值时是否将实际值置为另一端的数值
		/// </summary>
		public bool IsGoToAnotherEndWhenRefBiggerThenMax { get; set; }

		/// <summary>
		/// 参考值小于最小值时是否将实际值置为另一端的数值
		/// </summary>
		public bool IsGoToAnotherEndWhenRefSmallerThenMin { get; set; }

		/// <inheritdoc />
		public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			double realValue = RealValueMin;
			try
			{
				if(!double.TryParse(value + "", out double originValue))
				{
					throw new ArgumentException($"绑定值[{value + ""}]无法转为 double");
				}

				if(originValue < RefValueMin)
				{
					originValue = RefValueMin;
					if(IsGoToAnotherEndWhenRefSmallerThenMin)
					{
						originValue = RefValueMax;
					}
				}

				if(originValue > RefValueMax)
				{
					originValue = RefValueMax;
					if(IsGoToAnotherEndWhenRefBiggerThenMax)
					{
						originValue = RefValueMin;
					}
				}

				double ratio = (originValue - RefValueMin) / (RefValueMax - RefValueMin);
				double gap = ratio * (RealValueMax - RealValueMin);
				if(IsReversed)
				{
					realValue = RealValueMax - gap;
				}
				else
				{
					realValue = gap + RealValueMin;
				}
			}
			catch(Exception ex)
			{
				Console.WriteLine(ex);
				Debug.WriteLine($"[{nameof(ReferenceValueToRealValueConverter)}] Exception：{ex}");
			}
			return realValue;
		}

		/// <inheritdoc />
		public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}
